<script setup lang="ts">
import { defineProps, ref, defineEmits, computed } from 'vue'
import { baseURL } from '@/utils/request'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const uploadRef = ref<UploadInstance>()
const emit = defineEmits(['fileChange'])
const props = defineProps({
    avatar: String
})
const handleChange = (file: any) => {
    emit('fileChange', file.raw)
}

const avatar = computed(() => {
    if (props?.avatar?.includes('blob') || props?.avatar?.includes('http')) {

        return props?.avatar
    }
    return `${baseURL}/${props.avatar}`
})

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}
</script>

<template>
    <el-upload ref="uploadRef" class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed"
        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple :on-change="handleChange">
        <img v-if="props.avatar" :src="avatar" class="avatar" />
        <el-icon v-else class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
            </div>
        </template>
    </el-upload>
</template>

<style lang="less">
.avatar {
    width: 100px;
}
</style>